import java.util.ArrayList;
import java.util.Iterator;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.Reader;

import javax.xml.namespace.QName;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.Characters;
import javax.xml.stream.events.StartDocument;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;

public class Nodesreader {
	
	public Classroom read(String file) {
		String current = "";
		String nr = null, lastname = null, surname = null;
		
		ArrayList<String> subjects = new ArrayList<String>();
		ArrayList<Boolean> isVisited = new ArrayList<Boolean>();
		ArrayList<Student> students = new ArrayList<Student>();
		
		try {
			Reader reader = new FileReader(file);
			XMLInputFactory factory = XMLInputFactory.newInstance();
			XMLEventReader xmlEventReader = factory.createXMLEventReader(reader);

			while (xmlEventReader.hasNext()) {
				XMLEvent event = xmlEventReader.nextEvent();
				
				// start element
				if (event.isStartElement()) {
					StartElement startelement = event.asStartElement();
					current = startelement.getName().getLocalPart();
					
					// process the good stuff
					if (current.equals("student")) {
						// iterate attribs
						Iterator<Attribute> attributes = startelement.getAttributes();
						while (attributes.hasNext()) {
							Attribute attribute = attributes.next();
							
							// search required fields
							if (attribute.getName().toString().equals("nr"))
								nr = attribute.getValue();
							else if (attribute.getName().toString().equals("lastname"))
								lastname = attribute.getValue();
							else if (attribute.getName().toString().equals("surname"))
								surname = attribute.getValue();
							// search optional subjects
							else {
								if (!subjects.contains(attribute.getName().toString())) {
									subjects.add(attribute.getName().toString());
								}
								isVisited.add(Boolean.valueOf(attribute.getValue().toString()));
							}
						
						}

						// finally add student
						students.add(new Student(nr, lastname, surname, isVisited.toArray(new Boolean[isVisited.size()])));
						isVisited.clear();
					}
				} else if (event.isCharacters()) {
					// do a whole lot of nothing
				}
			}
		}
		catch (FileNotFoundException | XMLStreamException e) {
			// more nothingness
		}
		
		Classroom classroom = new Classroom(students.toArray(new Student[students.size()]), subjects.toArray(new String[subjects.size()]));
		
		return classroom;
	}	
}
